<?php

namespace App\HttpController\Admin;

use App\Model\AdminsModel;
use App\Model\ArticlesModel;
use App\Model\CategorysModel;
use App\Model\FormidsModel;
use App\Model\TmplmsgsModel;
use App\Utility\MiniProgram;
use App\Utility\Music;
use App\Utility\RedisTools;
use Carbon\Carbon;
use EasySwoole\EasySwoole\Logger;

class Article extends Auth{
    /**
     * 列表
     * @return bool|void
     * @throws \Throwable
     */
    public function index(){
        try{
            $request = $this->request();
            $params = $request->getRequestParam();
            //登陆信息
            $model = new AdminsModel();
            $user = $model->user($this->token);
            if($user['role_id'] > 1){
                $params['userid'] = $user['id'];
            }else{
                $params['userid'] = $params['userid'] ?? 0;
            }
            //获取用户可推送模板id数量
            $formModel = new FormidsModel();
            $todayUseTotal = $formModel->where('expires_at',time(),'>')
                ->where('userid',$user['user_id'])
                ->getAll();
            $model = new ArticlesModel();
            $list = $model->getAdminList($params);
            // 增加 分享/浏览 占比
            if(isset($list['data']) && count($list['data']) > 0){
                foreach ($list['data'] as $key => &$item){
                    if($item['share'] > 0){
                        $item['pre'] = ((string)floor(($item['share']/$item['view'])*10000)/100).'%';
                    }else{
                        $item['pre'] = '0%';
                    }
                }
            }
            $list['count_formid'] = count($todayUseTotal);
            return $this->writeJson(0,$list);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 详情
     * @return bool
     * @throws \Throwable
     */
    public function info(){
        try{
            $request = $this->request();
            $id = $request->getRequestParam('id') ?? 0;
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            $model = new ArticlesModel();
            $info = $model->select('id,cateid,title,title_color,thumb,music_name,backimg,hot,`lock`,music,content')->find($id);
            return $this->writeJson(0,$info);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 更新
     * @return bool
     * @throws \Throwable
     */
    public function update(){
        try{
            $request = $this->request();
            $data = $request->getRequestParam();
            //验证音乐编号的正确性
            $res = (new Music())->getMusic($data['music']);
            if($res === false){
                return $this->writeJson(1,null,'音乐编号不能解析，请重新填写');
            }
            $model = new ArticlesModel();
            if($data['id']){
                //修改
                $model->update($data);
                return $this->writeJson(0,null,'编辑成功');
            }else{
                //新增
                //获取用户ID
                $adminsModel = new AdminsModel();
                $user = $adminsModel->user($this->token);
                $data['created_at'] = Carbon::now();
                $data['userid'] = $user['id'];
                $data['rand'] = rand(1,10);
                $cmodel = new CategorysModel();
                $cate = $cmodel->inRandomOrder()->first();
                $data['cateid'] = $cate['id'];
                $model->create($data);
                return $this->writeJson(0,null,'新增成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 删除
     * @return bool
     * @throws \Throwable
     */
    public function destroy(){
        try{
            $request = $this->request();
            $id = $request->getRequestParam('id');
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            $model = new ArticlesModel();
            $model->destroy($id);
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }

    }
    /**
     * 批量删除
     * @return bool
     * @throws \Throwable
     */
    public function destroy_all(){
        try{
            $request = $this->request();
            $data= $request->getRequestParam('data');
            if(empty($data) || count($data) < 1){
                return $this->writeJson(1,null,'参数错误');
            }
            $model = new ArticlesModel();
            foreach ($data as $item){
                $model->destroy($item);
            }
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 模板推送，手机预览
     * @return bool
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\OrderByFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function push(){
        $request = $this->request();
        $data = $request->getRequestParam();
        $model = new TmplmsgsModel();
        $msg = $model->find(6);
        if (!$data['id'] || !$msg) {
            return $this->writeJson(1,null,'推送模板不存在了！');
        }
        //获取用户ID
        $adminsModel = new AdminsModel();
        $user = $adminsModel->user($this->token);
        //判断是否有可以formId
        $formModel = new FormidsModel();
        $formModel->where('expires_at',time(),'<=')->delete();
        $expire = time()+800;
        $formId = $formModel->where('userid',$user['user_id'])
            ->where('expires_at',$expire,'>')
            ->orderBy('id','ASC')
            ->first();
        if(!$formId){
            return $this->writeJson(1,null,'没有可用的FORMID了！');
        }
        $articlesModel = new ArticlesModel();
        $articlesInfo = $articlesModel->select('id,title')->find($data['id']);
        $msg['keywords'][0]->keyword2 = $articlesInfo['title'];
        $wechat = new MiniProgram();
        $sendData = [
            'touser'      => $formId['openid'],
            'template_id' => $msg['template_id'],
            'page'        => $msg['page'].'?id='.$data['id'].'&user_id='.$user['user_id'],
            'form_id'     => $formId['formid'],
            'data'        => $msg['keywords'][0],
            'emphasis_keyword' => '',
        ];
        $result = $wechat->sendTemplateMessage($sendData);
        if($result['errcode'] == 0){
            //删除该条formid信息
            $formModel->destroy($formId['id']);
            return $this->writeJson(0, null, '操作成功，请手机点击查看！');
        }else{
            if(($result['errcode'] == 41028) || ($result['errcode'] == 41029)){
                $formModel->destroy($formId['id']);
            }
            return $this->writeJson(1, $result, '推送失败，'.$result['chmsg']);
        }

    }
}
